<?php

namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Dypnsapi\Dypnsapi;
use app\api\logic\UserLogic;
use app\api\model\User;
use app\api\validate\LoginTokenValidate;
use app\Request;
use think\exception\ValidateException;
use think\facade\Log;

class UserController extends BaseController
{
    // 验证码登录
    public function loginByCode(Request $request) {
        $post = $request->post();

        // 本地或者测试环境执行此代码
        //if(env('ENV') == 'local' or env('ENV') == 'dev') {
        if($post['code'] == 'xxxx') {
            $data = UserLogic::getUserApi(52239);
            if(!$data) {
                $this->setError(\Debug::getDebug());
            }
            return $this->setSuccess($data);
        }
        //}

        try {
            $this->validate($post, LoginTokenValidate::class);
        } catch (ValidateException $e) {
            return $this->setError($e->getMessage());
        }

        $phone  = $post['phone'];
        $code   = $post['code'];

        $data = UserLogic::loginByCode($phone, $code);
        if(!$data) {
            return $this->setError(\Debug::getDebug());
        }
        return $this->setSuccess($data);
    }

    //获取当前登录人信息
    public function info(Request $request) {
        $userId = $this->getUserId();
        if(!$userId) {
            return $this->setError(\Debug::getDebug());
        }

        $data = UserLogic::getInfoByUserId($userId);
        if(!$data) {
            return $this->setError(\Debug::getDebug());
        }

        return $this->setSuccess($data);
    }

    // 一键登录
    public function loginByMobile(Request $request) {
        $token = $request->post('token');
        if(!$token) {
            return $this->setError('参数不完整,请重试');
        }

        $config = \config('ali');

        $accessKeyId = $config['accessKeyId'];
        $accessKeySecret = $config['accessKeySecret'];
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId('cn-hangzhou')->asDefaultClient()->options([]);

        try {
            $req = Dypnsapi::v20170525()->getMobile();
            $res = $req
                ->withAccessToken($token)
                ->debug(false) // Enable the debug will output detailed information
                ->request();
            $res = $res->toArray();

            if($res['Code'] != 'OK') {
                return $this->setError($res['Message'] ?? '请求失败.');
            }
            $phone = $res['GetMobileResultDTO']['Mobile'] ?? null;
            if(!$phone) {
                return $this->setError('获取手机号失败');
            }
        } catch (ClientException $exception) {
            Log::error('一键登录出错');
            Log::error($exception->getMessage());
            return $this->setError('一键登录失败');
        } catch (ServerException $exception) {
            Log::error('一键登录出错');
            Log::error($exception->getMessage());
            return $this->setError('一键登录失败.');
        } catch (\Throwable $e) {
            Log::error('一键登录出错');
            Log::error($e->getMessage());
            return $this->setError('一键登录失败..');
        }

        $data = UserLogic::loginByPhone($phone);
        if(!$data) {
            return $this->setError(\Debug::getDebug());
        }
        return $this->setSuccess($data);
    }

    // 修改昵称
    public function changeNickname(Request $request) {
        $userId = $this->getUserId();
        if(!$userId) {
            return $this->setError(\Debug::getDebug());
        }

        $nickName = $request->post('nickname');
        if(!$nickName) {
            return $this->setError('请提交昵称');
        }
        if(mb_strlen($nickName) > 50) {
            return $this->setError('昵称不合法,请重新输入');
        }

        $res = User::changeNickName($userId, $nickName);
        if(!$res) {
            return $this->setError('昵称修改失败,请重试');
        }
        return $this->setSuccess();
    }

    // 修改头像
    public function changeImage(Request $request) {
        $userId = $this->getUserId();
        if(!$userId) {
            return $this->setError(\Debug::getDebug());
        }

        $image = $request->post('image');
        if(!$image) {
            return $this->setError('请提交头像');
        }
        $res = User::changeImage($userId, $image);
        if(!$res) {
            return $this->setError('头像修改失败,请重新输入');
        }
        return $this->setSuccess();
    }

    // 注销账号
    public function logoff(Request $request) {
        if(!$request->isPost()) {
            return $this->setError('请求错误');
        }

        $userId = $this->getUserId();
        if(!$userId) {
            return $this->setError(\Debug::getDebug());
        }

        $res = UserLogic::logoff($userId);
        if(!$res) {
            return $this->setError('注销失败');
        }
        return $this->setSuccess();
    }
}